package ssau.knyazev.cafe.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import ssau.knyazev.common.UniException;
import ssau.knyazev.db.core.ConnectionHelper;




public class Order {

	private String orderID;
	private String userID;
	private String date;
	private String userName;
	private final static String loadQuery = "select co.order_id, co.user_id, co.order_date, cu.name from cafe_orders co, cafe_users cu where order_id = ? and co.user_id = cu.user_id";
	private final static String loadAllQuery = "select co.order_id, co.user_id, co.order_date, cu.name from cafe_orders co, cafe_users cu where co.user_id = cu.user_id";
	
	public String getOrderID() {
		return orderID;
	}

	public void setOrderID(String orderID) {
		this.orderID = orderID;
	}

	public String getUserID() {
		return userID;
	}

	public void setUserID(String userID) {
		this.userID = userID;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}
	
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}
	
	public static List<Order> loadAll() throws UniException{
		List<Order> orders = new LinkedList<Order>();
		Connection con = ConnectionHelper.getConnection();
		PreparedStatement state = null;
		try {
			state = con.prepareStatement(loadAllQuery);
			ResultSet rs = state.executeQuery();
			while (rs.next()){
				Order o = new Order();
				o.setOrderID(rs.getString(1));
				o.setUserID(rs.getString(2));
				o.setDate(rs.getString(3));
				o.setUserName(rs.getString(4));
				orders.add(o);
			}
			return orders;
		} catch (SQLException e) {
			throw new UniException("Could not perform query:\n" + loadQuery, e);
		} finally {
			ConnectionHelper.closeConnection(con, state);
		}
	}
	
	public static Order load(String orderID) throws UniException{
		Connection con = ConnectionHelper.getConnection();
		PreparedStatement state = null;
		Order result = null;
		try {
			state = con.prepareStatement(loadQuery);
			state.setString(1, orderID);
			ResultSet rs = state.executeQuery();
			if (rs.next()){
				result = new Order();
				result.setOrderID(rs.getString(1));
				result.setUserID(rs.getString(2));
				result.setDate(rs.getString(3));
				result.setUserName(rs.getString(4));
				return result;
			} else {
				throw new UniException("Not found order with ID = " + orderID);
			}
		} catch (SQLException e) {
			throw new UniException("Could not perform query:\n" + loadQuery, e);
		} finally {
			ConnectionHelper.closeConnection(con, state);
		}
	}

	
	
	public String toString(){
		return "Order #" + orderID + ": was made in " + date + " by " + userName + "(#" + userID + ")";
	}
	
}
